import {ElLoading} from 'element-plus'
import {MessageService} from './message'
import type {AxiosError, AxiosResponse} from 'axios'
import type {ApiResponse, ApiResult, RequestConfig} from '@/types/api'
import {ErrorCode, getErrorMessage, isAuthErrorCode, isPermissionErrorCode} from '@/constants/errorCodes'

// 声明环境变量类型
declare const process: {
  env: {
    NODE_ENV: 'development' | 'production' | 'test'
  }
}

/**
 * 响应处理器类
 */
export class ResponseHandler {
  private static loadingInstance: any = null

  /**
   * 处理成功响应
   */
  static handleSuccess<T>(
    response: AxiosResponse<ApiResponse<T>>,
    config?: RequestConfig
  ): ApiResult<T> {
    const { data } = response
    const result: ApiResult<T> = {
      success: true,
      data: data.data,
      status: response.status,
      headers: response.headers as Record<string, string>
    }

    // 显示成功消息 - 只有明确指定 showSuccess: true 时才显示
    if (!config?.silent && (config?.showSuccess === true)) {
      const message = config?.successMessage || data.message || '操作成功'
      MessageService.success(message)
    }

    // 关闭加载状态
    if (config?.loading) {
      this.closeLoading()
    }

    return result
  }

  /**
   * 处理错误响应
   */
  static handleError<T>(
    error: AxiosError<ApiResponse<T>>,
    config?: RequestConfig
  ): ApiResult<T> {
    const response = error.response
    const status = response?.status || 0
    const responseData = response?.data

    const result: ApiResult<T> = {
      success: false,
      status,
      headers: response?.headers as Record<string, string> || {},
      error: {
        code: responseData?.code || status,
        message: this.getErrorMessage(responseData, status),
        details: responseData?.details
      }
    }

    // 显示错误消息
    if (!config?.silent && (config?.showError !== false)) {
      const message = config?.errorMessage || result.error?.message || '请求失败'

      if (result.error?.code === ErrorCode.TOKEN_EXPIRED) {
        // 令牌过期不显示错误消息，由路由守卫处理
        console.warn('Token expired:', message)
      } else {
        MessageService.error(message)
      }
    }

    // 关闭加载状态
    if (config?.loading) {
      this.closeLoading()
    }

    // 记录错误日志
    this.logError(error, config)

    return result
  }

  /**
   * 显示加载状态
   */
  static showLoading(message = '加载中...'): any {
    this.closeLoading()
    this.loadingInstance = ElLoading.service({
      lock: true,
      text: message,
      background: 'rgba(0, 0, 0, 0.7)'
    })
    return this.loadingInstance
  }

  /**
   * 关闭加载状态
   */
  static closeLoading(): void {
    if (this.loadingInstance) {
      this.loadingInstance.close()
      this.loadingInstance = null
    }
  }

  /**
   * 获取错误消息
   */
  private static getErrorMessage(responseData: any, status: number): string {
    // 优先使用响应中的错误消息
    if (responseData?.message) {
      return responseData.message
    }

    // 使用错误码映射的消息
    if (responseData?.code) {
      return getErrorMessage(responseData.code)
    }

    // 使用HTTP状态码映射的消息
    if (status) {
      return getErrorMessage(status)
    }

    return '未知错误'
  }

  /**
   * 记录错误日志
   */
  private static logError(error: AxiosError, config?: RequestConfig): void {
    if (process.env.NODE_ENV === 'development') {
      console.group('🚨 API Error')
      console.error('Error:', error)
      console.error('Config:', config)
      console.error('Response:', error.response?.data)
      console.groupEnd()
    }

    // 生产环境可以发送错误到监控系统
    if (process.env.NODE_ENV === 'production') {
      // TODO: 集成错误监控服务（如 Sentry）
      // this.sendToMonitoring(error, config)
    }
  }

  /**
   * 检查是否需要重新登录
   */
  static shouldRelogin(error: AxiosError): boolean {
    const status = error.response?.status
    const code = (error.response?.data as any)?.code

    return isAuthErrorCode(status || code || 0)
  }

  /**
   * 检查是否为权限错误
   */
  static isPermissionError(error: AxiosError): boolean {
    const status = error.response?.status
    const code = (error.response?.data as any)?.code

    return isPermissionErrorCode(status || code || 0)
  }

  /**
   * 检查是否为网络错误
   */
  static isNetworkError(error: AxiosError): boolean {
    return !error.response && !!error.request
  }

  /**
   * 检查是否为服务器错误
   */
  static isServerError(error: AxiosError): boolean {
    const status = error.response?.status
    return !!(status && status >= 500 && status < 600)
  }

  /**
   * 检查是否为客户端错误
   */
  static isClientError(error: AxiosError): boolean {
    const status = error.response?.status
    return !!(status && status >= 400 && status < 500)
  }

  /**
   * 格式化API响应数据
   */
  static formatResponseData<T>(response: AxiosResponse<ApiResponse<T>>): T | undefined {
    return response.data?.data
  }

  /**
   * 创建请求配置
   */
  static createRequestConfig(options?: Partial<RequestConfig>): RequestConfig {
    return {
      loading: false,
      showSuccess: false,
      showError: true,
      silent: false,
      ...options
    }
  }
}

/**
 * 默认请求配置
 */
export const defaultRequestConfig: RequestConfig = {
  loading: false,
  showSuccess: false,
  showError: true,
  silent: false
}

/**
 * 创建带消息提示的请求配置
 */
export function createMessageConfig(
  successMessage?: string,
  errorMessage?: string,
  loading = false
): RequestConfig {
  return {
    loading,
    showSuccess: !!successMessage,
    showError: !!errorMessage,
    successMessage,
    errorMessage,
    silent: false
  }
}

/**
 * 创建静默请求配置
 */
export function createSilentConfig(): RequestConfig {
  return {
    loading: false,
    showSuccess: false,
    showError: false,
    silent: true
  }
}

/**
 * 创建加载中请求配置
 */
export function createLoadingConfig(message = '加载中...'): RequestConfig {
  return {
    loading: true,
    showSuccess: false,
    showError: true,
    silent: false,
    successMessage: undefined,
    errorMessage: undefined
  }
}